import constVal from './const.js';
let {
	blockShape,
	origin
} = constVal;

class Block {
	constructor(option) {
		this.type = option.type;

		if (!option.rotateIndex) {
			this.rotateIndex = 0;
		} else {
			this.rotateIndex = option.rotateIndex;
		}

		if (!option.timeStamp) {
			this.timeStamp = Date.now();
		} else {
			this.timeStamp = option.timeStamp;
		}
		if (!option.shape) { // init
			this.shape = blockShape[option.type].map(e => e.slice());
		} else {
			this.shape = option.shape;
		}
		
		if (!option.xy) { //初始坐标
			switch (option.type) {
				case 'I': // I
					this.xy = [0, 3];
					break;
				case 'L': // L
					this.xy = [-1, 4];
					break;
				case 'J': // J
					this.xy = [-1, 4];
					break;
				case 'Z': // Z
					this.xy = [-1, 4];
					break;
				case 'S': // S
					this.xy = [-1, 4];
					break;
				case 'O': // O
					this.xy = [-1, 4];
					break;
				case 'T': // T
					this.xy = [-1, 4];
					break;
				default:
					break;
			}
		} else {
			this.xy = option.xy;
		}
	}
	rotateShape(arr) {
		if (arr.length <= 0) {
			return [];
		}
		if (arr[0] && arr[0].length <= 0) {
			return [];
		}
		var lenRow = arr[0].length; //新的列数
		var lenCol = arr.length; //新的行数
		var res = new Array(lenRow).fill(0).map(function(row) {
			return new Array(lenCol).fill(0);
		});
		for (var i = 0; i < lenRow; i++) {
			for (var j = 0; j < lenCol; j++) {
				res[i][j] = arr[j][lenRow - i - 1];
			}
		}
		return res;
	}
	rotate() {
		const shape = this.shape;
		let result = this.rotateShape(shape); //向左旋转变形
		const nextXy = [
			this.xy[0] + origin[this.type][this.rotateIndex][0],
			this.xy[1] + origin[this.type][this.rotateIndex][1],
		];
		const nextRotateIndex = this.rotateIndex + 1 >= origin[this.type].length ?
			0 : this.rotateIndex + 1;
		return {
			shape: result,
			type: this.type,
			xy: nextXy,
			rotateIndex: nextRotateIndex,
			timeStamp: this.timeStamp,
		};
	}
	fall(n = 1) {
		return {
			shape: this.shape,
			type: this.type,
			xy: [this.xy[0] + n, this.xy[1]],
			rotateIndex: this.rotateIndex,
			timeStamp: Date.now(),
		};
	}
	right() {
		return {
			shape: this.shape,
			type: this.type,
			xy: [this.xy[0], this.xy[1] + 1],
			rotateIndex: this.rotateIndex,
			timeStamp: this.timeStamp,
		};
	}
	left() {
		return {
			shape: this.shape,
			type: this.type,
			xy: [this.xy[0], this.xy[1] - 1],
			rotateIndex: this.rotateIndex,
			timeStamp: this.timeStamp,
		};
	}
}

export default Block;
